#include "classdialog.h"
#include "ui_classdialog.h"
#include <QMessageBox>
#include <QSqlDatabase>
#include <QSqlQuery>
#include <QSqlError>

ClassDialog::ClassDialog(QWidget *parent) :
    QDialog(parent),
    ui(new Ui::ClassDialog)
{
    ui->setupUi(this);

    this->setWindowFlag(Qt::WindowContextHelpButtonHint, false);
    this->setWindowFlag(Qt::WindowMinimizeButtonHint, false);
}

ClassDialog::~ClassDialog()
{
    delete ui;
}

void ClassDialog::on_pushButton_clicked()
{
    QString _class = this->ui->class_lineedit->text();
    QString _group_name = this->ui->group_lineedit->text();
    if (_class.length() == 0 || _group_name.length() == 0) {
        QMessageBox::warning(this, "系统警告", "班级名称和组别均不能为空");
        return;
    }
    if (_group_name.length() >= 2) {
        QMessageBox::warning(this, "系统警告", "组别长度不能超过1个字符");
        return;
    }
    if (_class.contains('\'') || _class.contains('"') || _class.contains('\\') ||
            _group_name.contains('\'') || _group_name.contains('"') || _group_name.contains('\\')) {
        QMessageBox::warning(this, "系统警告", "班级名称和组别均不能包含'、\"和\\");
        return;
    }
    QSqlDatabase db = QSqlDatabase::addDatabase("QSQLITE", "class");
    db.setDatabaseName("data.db");
    if (!db.open()) {
        QMessageBox::critical(this, "系统错误", "无法打开数据库");
        return;
    }
    db.exec("INSERT INTO `class`(`name`, `group_name`) VALUES ('" + _class + "', '" + _group_name + "')");
    QSqlError err = db.lastError();
    if (err.isValid()) {
        QMessageBox::critical(this, "系统错误", QString("无法插入数据：") + err.databaseText());
        return;
    }
    db.close();
    QSqlDatabase::removeDatabase("class");
    this->close();
}

